package com.ken.rxhttp.http_api_impl

import android.util.Log
import com.ken.base_http_library.news.NewsResponse
import com.ken.rxhttp.news.JuHeNewBaseResponse
import okhttp3.Response
import rxhttp.wrapper.annotation.Parser
import rxhttp.wrapper.entity.ParameterizedTypeImpl
import rxhttp.wrapper.exception.ParseException
import rxhttp.wrapper.parse.AbstractParser
import java.io.IOException
import java.lang.reflect.Type

/**
 * @author by ken
 * Blog:
 * Date:2020/5/12
 * Description:
 */

@Parser(name = "Response")
open class ResponseParser<T> : AbstractParser<T> {
    val TAG = ResponseParser::class.java.name

    //以下两个构造方法是必须的
    protected constructor() : super()

    constructor(type: Class<T>) : super(type)

    @Throws(IOException::class)
    override fun onParse(response: okhttp3.Response): T {
        val type: Type = ParameterizedTypeImpl[JuHeNewBaseResponse::class.java, mType] //获取泛型类型
        val data: JuHeNewBaseResponse<T> = convert(response, type)   //获取Response对象
        val t = data.result                          //获取data字段
        var res = data.result as NewsResponse
        Log.e(TAG, data.reason)
        Log.e(TAG, "t........" + res.data.toString())
        if (data.error_code != 0 || t == null) { //code不等于200，说明数据不正确，抛出异常
            throw ParseException(data.error_code.toString(), data.reason, response)
        }
        return t
    }
}
